package com.jeecms.wicool.action.lottery;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.entity.assist.CmsVoteSubTopic;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.car.CarAdviser;
import com.jeecms.wicool.entity.car.CarOrder;
import com.jeecms.wicool.entity.car.CarOrderAppraise;
import com.jeecms.wicool.entity.lottery.ActiveConfig;
import com.jeecms.wicool.entity.lottery.LotteryConfig;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.car.CarOrderAppraiseMng;
import com.jeecms.wicool.manager.car.CarOrderMng;
import com.jeecms.wicool.manager.lottery.ActiveConfigMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

@Controller
public class ActiveConfigAct {
	private static final Logger log = LoggerFactory.getLogger(ActiveConfigAct.class);

	@RequestMapping("/activeConfig/v_list.do")
	public String list(String name,Integer status,String startTime,String endTime,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage( name, status, startTime, endTime,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		List<ActiveConfig> listActiveConfig=(List<ActiveConfig>)pagination.getList();
		List<Dictionary2> listActiveConfigStatus=DicMng.getList("activeConfig_status");
		Map<String,String> map = new HashMap<String,String>();
		 for(Dictionary2 d : listActiveConfigStatus){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 } 
		 for(ActiveConfig p : listActiveConfig){
			 if(map.containsKey(p.getStatus().toString())){
				 p.setStatusName(map.get(p.getStatus().toString()));
			 }
		 }
		 model.addAttribute("pagination", pagination);
		 model.addAttribute("listActiveConfigStatus", listActiveConfigStatus);
		model.addAttribute("name",name);
		model.addAttribute("status",status);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		return "lottery/list_activeConfig";
	}
	@RequestMapping("/activeConfig/v_edit.do")
	public String edit(Integer id, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		ActiveConfig activeConfig=manager.findById(id);
		TreeSet<LotteryConfig> lotterys= new TreeSet<LotteryConfig>(new Comparator(){
			@Override
			public int compare(Object arg0, Object arg1) {
				LotteryConfig a=(LotteryConfig) arg0;
				LotteryConfig b=(LotteryConfig) arg1;
				if(a.getId()<b.getId()){
					return -1;
				}else if(a.getId()>b.getId()){
					return 1;
				}
				return 0;
			}
		});
		lotterys.addAll(activeConfig.getLotteryConfigs());
//		for(int i=0;i<lotterys.size()-1;i++){
//			for(int j=1;j<lotterys.size();j++){
//				if(lotterys.g)
//			}
//		}
		activeConfig.setLotteryConfigs(lotterys);
		model.addAttribute("activeConfig", activeConfig);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("listShop",listShop);
		return "lottery/edit_activeConfig";
	}
	@RequestMapping("/activeConfig/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ActiveConfig activeConfig = manager.findById(id);
		
		model.addAttribute("activeConfig",activeConfig);
		
		return "lottery/view_activeConfig";
	}
	@RequestMapping("/activeConfig/o_save.do")
	public String save(ActiveConfig bean, Integer shopId,HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean.setShop(shopMng.findById(shopId));
		
		Set<LotteryConfig>lotterys=getLotterys(request);
		for(LotteryConfig lc:lotterys){
			lc.setActiveConfig(bean);
		}
		bean.setLotteryConfigs(lotterys);
		bean = manager.save(bean);
		log.info("save ActiveConfig id={}", bean.getId());
		cmsLogMng.operating(request, "ActiveConfig.log.save",  "id=" + bean.getId());
		return "redirect:v_list.do";
	}
	@SuppressWarnings("unchecked")
	private Set getLotterys(HttpServletRequest request){
		Enumeration paramNames=request.getParameterNames();
		Map<String,String> idMap = new HashMap<String,String>();
		Map<String,String> prizeNameMap = new HashMap<String,String>();
		Map<String,String> maxCountMap = new HashMap<String,String>();
		Map<String,String> dayCountMap = new HashMap<String,String>();
		Map<String,String> userMaxCountMap = new HashMap<String,String>();
		Map<String,String> proMap = new HashMap<String,String>();
		Map<String,String> indexMap = new HashMap<String,String>();
		
		List<Integer> numList=new ArrayList<Integer>();
		String paramName;
		while(paramNames.hasMoreElements()){
			paramName=(String) paramNames.nextElement();
			if(paramName.startsWith("lottery_id")){
				idMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_prizeName")){
				prizeNameMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_maxCount")){
				maxCountMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_dayCount")){
				dayCountMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_userMaxCount")){
				userMaxCountMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_pro")){
				proMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}if(paramName.startsWith("lottery_index")){
				indexMap.put(paramName.substring(paramName.length()-1, paramName.length()), request.getParameter(paramName));
			}
			if(paramName.startsWith("num")){
				numList.add(Integer.parseInt(request.getParameter(paramName)));
			}
		}
		SortedSet<LotteryConfig> lotterys = new TreeSet<LotteryConfig>();

		LotteryConfig lott;
		
		int maxNum=0;
		if(numList!=null&&numList.size()>0){
			Collections.sort(numList);
			maxNum=numList.get(numList.size()-1);
		}
		for(int i=0;i<maxNum+1;i++){
			 lott=new LotteryConfig();
			 lott.setP(i);
			boolean isOK=false;
			if(idMap.get(String.valueOf(i))!=null&&!idMap.get(String.valueOf(i)).equals("")){
				lott.setId(Integer.parseInt(idMap.get(String.valueOf(i))));
				isOK=true;
				}
			if(prizeNameMap.get(String.valueOf(i))!=null&&!prizeNameMap.get(String.valueOf(i)).equals("")){
			lott.setPrizeName(prizeNameMap.get(String.valueOf(i)));
			isOK=true;
			}if(maxCountMap.get(String.valueOf(i))!=null&&!maxCountMap.get(String.valueOf(i)).equals("")){
				lott.setMaxCount(Integer.parseInt(maxCountMap.get(String.valueOf(i))));
				isOK=true;
			}if(dayCountMap.get(String.valueOf(i))!=null&&!dayCountMap.get(String.valueOf(i)).equals("")){
				lott.setDayCount(Integer.parseInt(dayCountMap.get(String.valueOf(i))));
				isOK=true;
			}if(userMaxCountMap.get(String.valueOf(i))!=null&&!userMaxCountMap.get(String.valueOf(i)).equals("")){
				lott.setUserMaxCount(Integer.parseInt(userMaxCountMap.get(String.valueOf(i))));
				isOK=true;
			}if(proMap.get(String.valueOf(i))!=null&&!proMap.get(String.valueOf(i)).equals("")){
				lott.setPro(Integer.parseInt(proMap.get(String.valueOf(i))));
				isOK=true;
			}if(indexMap.get(String.valueOf(i))!=null&&!indexMap.get(String.valueOf(i)).equals("")){
				lott.setIndex(indexMap.get(String.valueOf(i)));
				isOK=true;
			}
			if(isOK==true){
				lotterys.add(lott);
			}
		}
		return lotterys;
	}
	@RequestMapping("/activeConfig/o_update.do")
	public String update(ActiveConfig bean,Integer shopId,String name,Integer status,String startTime,String endTime,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		bean.setShop(shopMng.findById(shopId));
		Set<LotteryConfig>lotterys=getLotterys(request);
		
		bean=manager.update(bean);
		String[] delLotteryId=request.getParameter("delLotteryId").split(",");
		manager.updateLotterys(bean,lotterys,delLotteryId);
		model.addAttribute("message", "global.success");
		log.info("update ActiveConfig success. id={}", bean.getId());
		cmsLogMng.operating(request, "ActiveConfig.log.update",  "id=" + bean.getId());
		return list(null, null, null, null, pageNo, request, model);
	}
	@RequestMapping("/activeConfig/o_open.do")
	public String open(Integer id,String name,Integer status,String startTime,String endTime,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ActiveConfig activeConfig = manager.findById(id);
		
		activeConfig.setStatus(1);
		manager.update(activeConfig);
		
		model.addAttribute("name",name);
		model.addAttribute("status",status);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		
		return list(name, status, startTime, endTime, pageNo, request, model);
	}
	@RequestMapping("/activeConfig/o_close.do")
	public String close(Integer id,String name,Integer status,String startTime,String endTime,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ActiveConfig activeConfig = manager.findById(id);
		
		activeConfig.setStatus(0);
		manager.update(activeConfig);
		
		model.addAttribute("name",name);
		model.addAttribute("status",status);
		model.addAttribute("startTime",startTime);
		model.addAttribute("endTime",endTime);
		
		return list(name, status, startTime, endTime, pageNo, request, model);
	}
	@RequestMapping("/activeConfig/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		ActiveConfig activeConfig = new ActiveConfig();
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("activeConfig", activeConfig);
		model.addAttribute("listShop", listShop);
		return "lottery/add_activeConfig";
	}
	@RequestMapping("/activeConfig/o_delete.do")
	public String delete(Integer[] ids, String name,Integer status,String startTime,String endTime,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ActiveConfig[] beans = manager.deleteByIds(ids);
		for (ActiveConfig bean : beans) {
			log.info("delete ActiveConfig id={}", bean.getId());
			cmsLogMng.operating(request, "ActiveConfig.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getName());
		}
		return list(name, status, startTime,endTime, status, request, model);
	}
	private WebErrors validateSave(ActiveConfig bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		ActiveConfig entity = manager.findById(id);
		if (errors.ifNotExist(entity, ActiveConfig.class, id)) {
			return true;
		}
		return false;
	}
	@Autowired
	private ActiveConfigMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private WiShopInfoMng shopMng;
}
